<template>
  <TabBar :order-statistics="orderStatistics" @active-handle="activeHandle" />
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <label style="margin-right: 5px">订单号:</label>
        <el-input v-model="number" placeholder="请输入订单号：" style="width: 15%" clearable @clear="getOrderPage"
          @keyup.enter="getOrderPage" />
        <label style="margin: 0 10px">手机号:</label>
        <el-input v-model="phone" placeholder="请输入手机号：" style="width: 15%" clearable @clear="getOrderPage"
          @keyup.enter="getOrderPage" />
        <label style="margin: 0 10px">下单时间:</label>
        <el-date-picker v-model="dateValue" type="daterange" unlink-panels format="YYYY-MM-DD"
          value-format="YYYY-MM-DD HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
          :shortcuts="shortcuts" clearable @clear="getOrderPage" />
        <el-button type="primary" style="margin-left: 10px" @click="getOrderPage">查询</el-button>
      </div>
    </template>
    <el-table :data="orders" style="width: 100%">
      <el-table-column prop="businessName" label="商家" />
      <el-table-column prop="number" label="订单号" />
      <el-table-column v-if="[2, 3, 4].includes(orderStatus)" key="orderDishes" prop="orderDishes" label="订单菜品" />
      <el-table-column v-if="[0].includes(orderStatus)" prop="status" label="订单状态">
        <template #default="{ row }">
          <span>{{ getOrderStatus(row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="consignee" label="用户名" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="address" label="地址" />
      <el-table-column v-if="[0, 2, 6].includes(orderStatus)" prop="orderTime" label="下单时间" />
      <el-table-column v-if="[3, 4].includes(orderStatus)" prop="estimatedDeliveryTime" label="预计送达时间" />
      <el-table-column v-if="[5].includes(orderStatus)" prop="deliveryTime" label="送达时间" />
      <el-table-column v-if="[0, 2, 5].includes(orderStatus)" key="amount" prop="amount" label="实收金额" align="center">
        <template #default="{ row }">
          <span>￥{{ decimalsReplenish(row.amount) }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="[6].includes(orderStatus)" prop="cancelTime" label="取消时间" />
      <el-table-column v-if="[6].includes(orderStatus)" prop="cancelReason" label="取消原因" />
      <el-table-column v-if="[6].includes(orderStatus)" prop="payStatus" label="支付状态" align="center">
        <template #default="{ row }">
          <span>{{ getPayStatus(row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="[2, 3, 4, 5].includes(orderStatus)" key="remark" prop="remark" label="备注" align="center" />
      <el-table-column v-if="[2, 3, 4].includes(orderStatus)" key="tablewareNumber" prop="tablewareNumber" label="餐具数量"
        align="center" min-width="80" />
      <el-table-column label="操作" width="240" align="center">
        <template #default="{ row }" v-if="userStore.rule !== 'admin'">
          <div class="operate">
            <div class="left">
              <el-button v-if="isActionButtonVisible(row.status, 'accept')" type="primary" size="small"
                @click="changeOrderStatus(row.id, row.status)">
                接单
              </el-button>
              <el-button v-if="isActionButtonVisible(row.status, 'deliver')" type="primary" size="small"
                @click="changeOrderStatus(row.id, row.status)">
                派送
              </el-button>
              <el-button v-if="isActionButtonVisible(row.status, 'complete')" type="primary" size="small"
                @click="changeOrderStatus(row.id, row.status)">
                完成
              </el-button>
            </div>
            <div class="center">
              <el-button v-if="isActionButtonVisible(row.status, 'reject')" size="small" type="danger"
                @click="cancelHandle(row)">
                拒单
              </el-button>
              <el-button v-if="isActionButtonVisible(row.status, 'cancel')" size="small" type="danger"
                @click="cancelHandle(row)">
                取消
              </el-button>
            </div>
            <div class="right">
              <el-button size="small" @click="detailHandle(row.id)"> 查看 </el-button>
            </div>
          </div>
        </template>
        <template #default="{ row }" v-else>
          <div> <el-button size="small" @click="detailHandle(row.id)"> 查看 </el-button></div>
        </template>
      </el-table-column>
       <template #empty>
         <el-empty />
      </template>
    </el-table>
    <template #footer>
      <!-- 分页条 -->
      <Pagination :page="page" :pageSize="pageSize" :total="total" @onSizeChange="onSizeChange"
        @onPageChange="onPageChange" />
    </template>
    <!-- 取消弹窗 -->
    <el-dialog v-model="cancelDialogVisible" :title="dialogTitle + '订单'" width="500"
      :before-close="() => ((cancelDialogVisible = false), (reason = ''))" :show-close="false">
      <el-form>
        <el-form-item :label="dialogTitle + '原因'" prop="label">
          <el-select v-model="reason" :placeholder="'请选择' + dialogTitle + '原因'">
            <el-option v-for="item in dialogTitle === '取消' ? cancelrReasonList : cancelOrderReasonList"
              :key="item.value" :value="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="reason === '其他原因'" label="其他原因:">
          <el-input v-model="remark" type="textarea" :placeholder="'请填写您' + dialogTitle + '的原因（限20字内）'"
            maxlength="20" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="(cancelDialogVisible = false), (reason = '')">取消</el-button>
          <el-button type="primary" @click="submitHandle">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { decimalsReplenish } from '@/utils/index'
import TabBar from './components/TabBar.vue'
import {
  cancelOrderAPI,
  completeOrderAPI,
  confirmOrderAPI,
  deliveryOrderAPI,
  getOrderStatisticsAPI,
  rejectOrderAPI,
} from '@/api/business/ordet'
import { OrderResult, OrderStatistics } from '@/types/order'
import {
  cancelOrderReasonList,
  cancelrReasonList,
  getPayStatus,
  getOrderStatus,
  OrderStatusEnum,
  DialogTitleEnum,
  shortcuts,
  isActionButtonVisible,
} from './constant'
import { useUserStore } from '@/stores/userStore'
// 订单搜索模块钩子函数
import useOrderSearch from './useOrderPage'
// 订单分页搜索
const { orders, phone, number, page, pageSize, total, orderStatus, dateValue, activeHandle, getOrderPage } =
  useOrderSearch()

import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getAdminOrderStatisticsAPI } from '@/api/admin/ordet'
const router = useRouter()
// 跳转到订单详细
const detailHandle = async (id: number) => {
  router.push({ path: 'order/detail', query: { id } })
}

// 待接单/待派送/派送中订单数量
let orderStatistics = ref({} as OrderStatistics)
const userStore = useUserStore()
/**
 * 各个状态的订单数量统计
 */
const getOrderStatistics = async () => {
  let params = {
    businessId: userStore.rule === 'admin' ? undefined : userStore.user.id,
  }
  if (userStore.rule === 'admin') {
    let { data } = await getAdminOrderStatisticsAPI()
    orderStatistics.value = data
  } else {
    let { data } = await getOrderStatisticsAPI(params)
    orderStatistics.value = data
  }
}
const orderId = ref(0) // 订单id
const cancelDialogVisible = ref(false) //取消，拒单弹窗
const dialogTitle = ref('') //取消，拒绝弹窗标题
const reason = ref('') //取消，拒绝原因
const remark = '' //自定义原因
// 接单/派送/完成订单
const changeOrderStatus = async (id: number, status: number) => {
  try {
    if (status === OrderStatusEnum.TO_BE_CONFIRMED) {
      await confirmOrderAPI(id)
      ElMessage.success('接单成功')
    } else if (status === OrderStatusEnum.TO_BE_DELIVERED) {
      await deliveryOrderAPI(id)
      ElMessage.success('开始派送')
    } else if (status === OrderStatusEnum.IN_DELIVERY) {
      await completeOrderAPI(id)
      ElMessage.success('订单已完成')
    }
    getOrderPage()
  } catch (error) {
    ElMessage.error(error || '操作失败')
  }
}
// 取消/拒绝订单
const cancelHandle = (row: OrderResult) => {
  if (row.status === 2) {
    dialogTitle.value = DialogTitleEnum.REJECT
  } else {
    dialogTitle.value = DialogTitleEnum.CANCEL
  }
  orderId.value = row.id
  cancelDialogVisible.value = true
}
// 确认取消/拒绝原因
const submitHandle = async () => {
  try {
    if (dialogTitle.value === DialogTitleEnum.CANCEL) {
      await cancelOrderAPI({ id: orderId.value, cancelReason: reason.value })
      ElMessage.success('取消成功')
    } else {
      await rejectOrderAPI({
        id: orderId.value,
        rejectionReason: reason.value,
      })
      ElMessage.success('拒绝成功')
    }
    cancelDialogVisible.value = false
    getOrderPage()
  } catch (error) {
    ElMessage.error(error || '操作失败')
  }
}

const onSizeChange = (num: number) => {
  pageSize.value = num
  getOrderPage()
}
const onPageChange = (num: number) => {
  page.value = num
  getOrderPage()
}
watch(
  () => orders.value,
  () => {
    //nextTick可以确保在数据变化导致的 DOM 更新完成后执行特定的操作，帮助你处理异步操作与 DOM 更新的顺序，以及获取更新后的 DOM 状态。
    nextTick(async () => {
      // console.log(newVal)
      await getOrderStatistics()
    })
  },
  // 立即执行一次
  { immediate: true },
)
onMounted(async () => {
  await Promise.all([getOrderPage(), getOrderStatistics()])
})
</script>
<style scoped lang="scss">
.page-container{
  height: calc(100% - 60px);
  display: flex;
  flex-direction: column;
  flex: 1;
}
.operate {
  display: inline-flex;
  margin: 0 20px;

  .left,
  .center,
  .right {
    // display: flex;
    flex: 1;
    align-items: center;
  }
}

.left .el-button,
.center .el-button,
.right .el-button {
  margin-left: 10px;
}
</style>
